#include "CButtonUI.h"
#include "CInputManager.h"
#include "CDirectWrite.h"


CButtonUI::CButtonUI(bool isMovable)
{
	m_sButton = NULL;
	m_Text.clear();
	m_nTextOffsetX = 0;
	m_nTextOffsetY = 0;

	SetType(CUIFactory::BUTTON);

	m_nMouseXOff = 0;
	m_nMouseYOff = 0;
	m_bMoving = false;

	SetIsMovable(isMovable);
}


CButtonUI::CButtonUI(std::string img, bool isMovable)
{
	m_sButton = CRender::GetInstance()->LoadTexture2DFromFile(img);
	m_Text.clear();
	m_nTextOffsetX = 0;
	m_nTextOffsetY = 0;

	SetType(CUIFactory::BUTTON);

	m_nMouseXOff = 0;
	m_nMouseYOff = 0;
	m_bMoving = false;

	SetIsMovable(isMovable);
}


void CButtonUI::LoadButtonImage(std::string img)
{
	if(m_sButton == NULL)
	{
		m_sButton = CRender::GetInstance()->LoadTexture2DFromFile(img);
	}
}


CButtonUI::~CButtonUI()
{
	
}


void CButtonUI::Update(double delta)
{
	D3DXVECTOR3 pos = GetPostion();

	if(GetIsMovable())
	{
		if(CInputManager::GetInstance()->MouseButtonDown(LEFTMOUSE_BUTTON))
		{
			int x = CInputManager::GetInstance()->MouseGetPosX();
			int y = CInputManager::GetInstance()->MouseGetPosY();

			if(x >= pos.x && x <= pos.x + m_sButton->m_Width && y >= pos.y && y <= pos.y + m_sButton->m_Height && !m_bMoving)
			{
				m_nMouseXOff = x - pos.x;
				m_nMouseYOff = y - pos.y;
				m_bMoving = true;
			}
		}
		else
		{
			m_nMouseXOff = 0;
			m_nMouseYOff = 0;
			m_bMoving = false;
		}
	}

	if(m_bMoving)
	{
		pos.x = CInputManager::GetInstance()->MouseGetPosX() - m_nMouseXOff;
		pos.y = CInputManager::GetInstance()->MouseGetPosY() - m_nMouseYOff;
		SetPositon(pos);
	}

	D3DXMATRIX scale;
	D3DXMATRIX mat;

	D3DXMatrixScaling(&scale, (float)m_sButton->m_Width, (float)m_sButton->m_Height, 1.0f);
	D3DXMatrixTranslation(&mat, float(m_sButton->m_Width / 2.0f) + pos.x, 768.0f - float(m_sButton->m_Height / 2.0f) - pos.y, 0.1f);

	m_sButton->m_pSprite->matWorld = scale * mat;
}


void CButtonUI::Render()
{
	CRender::GetInstance()->Render2D(m_sButton->m_pSprite);

	if(m_Text.size() > 0)
	{
		CDirectWrite::GetInstance()->DrawText(CDirectWrite::FPS, m_Text, GetPostion().x + m_nTextOffsetX, GetPostion().y + m_nTextOffsetY, D3DXCOLOR(0.0f, 0.0f, 0.0f, 1.0f));
	}
}